package com.ihd.ihardware.view.tzc.me.view;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.ihd.ihardware.R;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.databinding.ActivityInfoBinding;
import com.ihd.ihardware.pojo.EmptyRes;
import com.ihd.ihardware.pojo.FileRes;
import com.ihd.ihardware.pojo.UserInfoRes;
import com.ihd.ihardware.view.tzc.me.viewmodel.InfoViewModel;

import java.io.File;
import java.util.Arrays;

import cn.wowjoy.commonlibrary.adapter.DialogListAdapter;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.ImageUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import cn.wowjoy.commonlibrary.widget.MDialog;

public class InfoActivity extends BaseActivity<ActivityInfoBinding, InfoViewModel> {

    private MDialog mBottomDG;
    public static final int PHOTO_PICKED_WITH_PATH = 3022;
    public static final int CAMERA_WITH_DATA = 3023;
    private UserInfoRes.DataBean ud;
    private String avatar = "";
    private String nickname = "";
    private boolean isReturn = false;

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(true).init();
        binding.mtitlebar.setTitle("个人信息");
        binding.mtitlebar.setLeftImageResource(R.drawable.ic_back);
        binding.mtitlebar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveAlert();
            }
        });

        ud = new Gson().fromJson(SPUtils.getString(AppConstans.USER_INFO, ""), UserInfoRes.DataBean.class);
        if (!TextUtils.isEmpty(ud.getAvatar())) {
            avatar = ud.getAvatar();
            Glide.with(getApplicationContext())
                    .load(Uri.parse(ud.getAvatar()))
                    .apply(RequestOptions.circleCropTransform())
                    .into(binding.headIV);
        }
        binding.idTV.setText(ud.getUserId());
        binding.sexTV.setText(ud.getSex() == 1 ? "男" : "女");
        binding.nickTV.setText(ud.getNickName());
        nickname = ud.getNickName();

        binding.headIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomDG = DialogUtils.BottomListDialog(InfoActivity.this, Arrays.asList("拍照", "从相册中选择"), new DialogListAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, String data) {
                        mBottomDG.cancel();
                        if (data.equals("拍照")) {
                            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri imguri = Uri.fromFile(new File(AppConstans.BASE_PATH + AppConstans.HEAD_PATH));
                            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imguri);
                            startActivityForResult(openCameraIntent, CAMERA_WITH_DATA);
                        } else {
                            Intent intent = new Intent(Intent.ACTION_PICK);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, PHOTO_PICKED_WITH_PATH);
                        }
                    }
                });
            }
        });

        binding.nickTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomDG = DialogUtils.inputDialog(InfoActivity.this, binding.nickTV.getText().toString());
                mBottomDG.setMsgCallback(new MDialog.interfaceEdit() {
                    @Override
                    public void Receive(String message) {
                        binding.nickTV.setText(message);
                        nickname = message;
                    }
                });
            }
        });

        setRx(AppConstans.UPDATE, new BaseConsumer<FileRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(InfoActivity.this);
            }

            @Override
            protected void onSuccess(FileRes mLiveData) {
                DialogUtils.dismiss(InfoActivity.this);
                avatar = mLiveData.getData().getUrl();
                Glide.with(getApplicationContext())
                        .load(Uri.parse(avatar))
                        .apply(RequestOptions.circleCropTransform())
                        .into(binding.headIV);
                isReturn = false;
                viewModel.updateInfo(avatar, nickname, ud.getSex(), ud.getBirthDay(), ud.getHeight(), ud.getWeight());
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(InfoActivity.this, error.getMessage());
                DialogUtils.dismiss(InfoActivity.this);
            }
        });

        setRx(AppConstans.UPDATEINFO, new BaseConsumer<EmptyRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(InfoActivity.this);
            }

            @Override
            protected void onSuccess(EmptyRes mLiveData) {
                DialogUtils.dismiss(InfoActivity.this);
                ud.setAvatar(avatar);
                ud.setNickName(nickname);
                SPUtils.putString(AppConstans.USER_INFO, new Gson().toJson(ud, UserInfoRes.DataBean.class));
                if (isReturn)
                    finish();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(InfoActivity.this, error.getMessage());
                DialogUtils.dismiss(InfoActivity.this);
            }
        });
    }

    private void saveAlert() {
        if (!nickname.equals(ud.getNickName()))
            mBottomDG = DialogUtils.alertDialog(this, MDialog.DG_TYPE.ALERT, "是否保存修改", "取消", "保存", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mBottomDG.cancel();
                    finish();
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mBottomDG.cancel();
                    isReturn = true;
                    viewModel.updateInfo(avatar, nickname, ud.getSex(), ud.getBirthDay(), ud.getHeight(), ud.getWeight());
                }
            });
        else
            finish();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_info;
    }

    @Override
    protected Class getViewModelClass() {
        return InfoViewModel.class;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String path = AppConstans.BASE_PATH + AppConstans.HEAD_PATH_S;
            switch (requestCode) {
                case CAMERA_WITH_DATA:
                    File f = ImageUtils.zoomImageFile(AppConstans.BASE_PATH + AppConstans.HEAD_PATH, path, 1080);
                    if (f != null)
                        viewModel.updateHead(f);
                    break;
                case PHOTO_PICKED_WITH_PATH:
                    final Uri uri = data.getData();
                    if (uri != null) {
                        File f0 = ImageUtils.zoomImageFile(ImageUtils.uri2path(this, uri), path, 1080);
                        if (f0 != null)
                            viewModel.updateHead(f0);
                    }
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        saveAlert();
    }
}
